/**
 * Created by qiang on 2017-03-20 .
 */
var params;
var self;

var app = new Vue({
	el: '#app',
	data: {
		pageType: "specifyCity",
		provinceList: common.provinceName,
		cities: [],
		Province: "-1",
		City: "-1",
		UserNo: "",
		userList: [],
		userInfo: {},
		searchKey: "",
		currPage: 0,
		isLoading: false,
		noData: false,
        scrollTop: 0
	},
	created: function () {
		self = this;
		params = common.getParamsFromURL(window.location);
		self.pageType = params.type;
		switch (self.pageType) {
			case 'specifyCity':
				document.title = '指定城市'
				break;
			case 'specifyID':
				document.title = '指定 ID'
				break;
			case 'city':
				document.title = '同城匹配'
				break;
			case 'country':
				document.title = '全网匹配'
				break;
		}
	},
	mounted: function() {
		common.auth(function() {
			if (sessionStorage.getItem("IsNewUser") != 'T') {
				self.getUserDetail();
			} else {
				self.userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
                $(".loading-bg").hide();
                if (self.pageType == 'city') {
                    self.getWXConfig();
                } else if (self.pageType == 'country') {
                    self.search();
                }
			}
		});
        common.YMCount();
	},
	watch: {
		Province: function (val) {
			self.currPage = 0;
			self.cities = common.getCity(parseInt(val));
		},
        City: function (val) {
			self.currPage = 0;
		}
	},
	computed: {
		addNum: function () {
			return self.userInfo.FreeAddNum + self.userInfo.ShareAddNum + self.userInfo.PaidAddNum;
		}
	},
	methods: {
        moreAddNum: function () {
            weui.confirm('更多积分。', {
                buttons: [{
                    label: '充值',
                    type: 'primary',
                    onClick: function() {
                        location.href = 'recharge.html'
                    }
                }, {
                    label: '分享',
                    type: 'primary',
                    onClick: function() {
                        location.href = 'share.html'
                    }
                }, {
                    label: '返回',
                    type: 'default',
                    onClick: function() {
                        // location.href = 'share.html'
                    }
                }]
            });
        },
        previewImg: function (url) {
            var imgUrl = url.indexOf('http') < 0 ? window.location.origin + url : url;
            wx.previewImage({
                current: imgUrl, // 当前显示图片的http链接
                urls: [imgUrl] // 需要预览的图片http链接列表
            });
        },
        getWXConfig: function () {
            var getWXConfigCallBack = function (data) {
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: data.appId, // 必填，公众号的唯一标识
                    timestamp: parseInt(data.timeStamp), // 必填，生成签名的时间戳
                    nonceStr: data.nonceStr, // 必填，生成签名的随机串
                    signature: data.signature,// 必填，签名，见附录1
                    jsApiList: ['getLocation', 'previewImage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                });

                wx.ready(function () {
                    wx.getLocation({
                        type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                        success: function (res) {
                            // weui.alert(JSON.stringify(res));
                            // var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                            // var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                            /* var speed = res.speed; // 速度，以米/每秒计
                            var accuracy = res.accuracy; // 位置精度*/
                            var options = {
                                lat: res.latitude,
                                lng: res.longitude
                            };
                            var getCityByLocationCallBack = function (response) {
                                self.userInfo.userProvince = common.provinceName.indexOf(response.province.replace(/省|特别行政区|自治区/, '')) + 1;
                                self.userInfo.userCity = common.getCity(common.provinceName.indexOf(response.province.replace(/省|特别行政区|自治区/, '')) + 1).indexOf(response.city);
                                self.search();
                            }
                            service.getCityByLocation(options, getCityByLocationCallBack);
                        }
                    });
                })
            }
            service.getWXConfig({url: window.location.href}, getWXConfigCallBack)
        },
		formatNum: function (num) {
			return parseInt(num)
		},
		jumpToMB: function (openId) {
            var ScrollObj = {
                currPage: self.currPage,
                scrollTop: self.scrollTop
            }
            sessionStorage.setItem('MScrollTopObj', JSON.stringify(ScrollObj));
			location.href = 'message_board.html?openid=' + openId
		},
		getUserDetail: function () {
			service.getUserDetail({}, function(data) {
				console.log(data)
				if (data && data.userInfo)  {
					self.userInfo = data.userInfo;
				}
				if (self.pageType == 'city' || self.pageType == 'country') {
					self.search();
				}
				$(".loading-bg").hide();
			})
		},
		isRegisterSearch: function (type) {

            var options = {
                options: {
                    "skip": self.currPage * 20,
                    "limit": 20
                }
            };

            var scrollTopObj = sessionStorage.getItem('MScrollTopObj') ? JSON.parse(sessionStorage.getItem('MScrollTopObj')) : null;
            if (scrollTopObj) {
                self.currPage = scrollTopObj.currPage;
                options.options.skip = 0;
                options.options.limit = (self.currPage + 1) * 20;
            }
            switch (self.pageType) {
                case 'specifyCity':
                   // console.log(self.City)
                   // console.log(self.Province)
                    if (self.Province == '-1') {
                        weui.alert("请先选择指定省份")
                        return
                    }
                    options.City = self.City != '-1' ? self.City : ''
                    options.Province = self.Province != '-1' ? self.Province : ''
                    break;
                case 'specifyID':
                    if (!self.UserNo) {
                        weui.alert("请先输入指定ID")
                        return
                    }
                    options.UserNo = self.UserNo;
                    break;
                case 'city':
                    options.SelectValue = self.searchKey;
                    options.SelectType = "TheCity";
                    break;
                case 'country':
                    options.SelectValue = self.searchKey;
                    options.SelectType = "WholeCountry";
                    break;
            }
            var searchCallBack = function(res) {
              //  console.log(res);
                for (var i = 0; i < res.data.length; i++) {
                    if (res.data[i].Province && res.data[i].City) {
                        res.data[i].cityAttr = common.getCity(res.data[i].Province)[parseInt(res.data[i].City)];
                    }
                    if (res.data[i].Birthday) {
                        res.data[i].age = new Date().getFullYear() - parseInt(res.data[i].Birthday.substr(0, 4)) + 1;
                        res.data[i].constellation = common.getAstro(new Date(res.data[i].Birthday).getMonth() + 1, new Date(res.data[i].Birthday).getDate());
                    }
                }
                self.noData = res.data && res.data.length < 20;
                var userList = type == 'new' ? [] : self.userList;
                self.userList = userList.concat(res.data)
                if (res.count == 0 && self.pageType == 'specifyID') {
                    weui.alert('ID不存在或已是好友。');
                }
                self.isLoading = false;
                self.$nextTick(function () {
                    common.lazyLoadImg();
                    if (scrollTopObj) {
                        document.querySelector(".user-list").scrollTop = scrollTopObj.scrollTop;
                        sessionStorage.removeItem('MScrollTopObj');
                        scrollTopObj = null;
                    }
                });
            };
            service.getUserList(options, searchCallBack);
        },
		unRegisterSearch: function (type) {
            var options = {
                options: {
                    "skip": self.currPage * 20,
                    "limit": 20
                },
				Sex: self.userInfo.sex == 1 ? '男' : '女'
            };
            switch (self.pageType) {
                case 'specifyCity':
                  //  console.log(self.City)
                  //  console.log(self.Province)
                    if (self.Province == '-1') {
                        weui.alert("请先选择指定省份")
                        return
                    }
                    options.City = self.City != '-1' ? self.City : ''
                    options.Province = self.Province != '-1' ? self.Province : ''
                    break;
                case 'specifyID':
                    if (!self.UserNo) {
                        weui.alert("请先输入指定ID")
                        return
                    }
                    options.UserNo = self.UserNo;
                    break;
                case 'city':
                    options.Province = self.userInfo.userProvince;
                    options.City = self.userInfo.userCity;
                    break;
                case 'country':
                    options.SelectValue = self.searchKey;
                    options.SelectType = "WholeCountry";
                    break;
            }
            var searchCallBack = function(res) {
              //  console.log(res);
                for (var i = 0; i < res.data.length; i++) {
                    res.data[i].cityAttr = common.getCity(res.data[i].Province)[parseInt(res.data[i].City)];
					res.data[i].age = new Date().getFullYear() - parseInt(res.data[i].Birthday.substr(0, 4)) + 1;
					res.data[i].constellation = common.getAstro(new Date(res.data[i].Birthday).getMonth() + 1, new Date(res.data[i].Birthday).getDate());
                }
                if (res.data && res.data.length < 20) {
                    self.noData = true
                }
                var userList = type == 'new' ? [] : self.userList;
                self.userList = userList.concat(res.data)
                if (res.count == 0 && self.pageType == 'specifyID') {
                    weui.alert('ID不存在或已是好友。');
                }
                self.isLoading = false;
            };
            service.getUnRegisterUserList(options, searchCallBack);
        },
		search: function (type) {
            if (type === 'new') self.currPage = 0
			if (sessionStorage.getItem("IsNewUser") == 'T') {
				self.unRegisterSearch(type);
			} else {
				self.isRegisterSearch(type);
			}
		},
		addFriend: function (item) {
            if (sessionStorage.getItem("IsNewUser") == 'T') {
                weui.alert("请先完成注册", function() {
                    location.href = 'userInfo.html';
                })
				return;
            }
			if (item.FriendId) {
                weui.alert("该用户已是好友");
                return;
            }
            if (item.AddId) {
                self.refreshMakeFriend(item);
                return;
            }
			if (self.addNum <= 0) {
//				weui.confirm("可加好友次数不足，你可以：");
				weui.confirm('积分不足，分享你专属的公众号二维码，双方都可获得1积分。', {
					buttons: [{
						label: '获得更多次数',
						type: 'primary',
						onClick: function() {
							location.href = 'power.html'
						}
					}, {
						label: '返回',
						type: 'default',
						onClick: function() {

						}
					}]
				});
			} else {
				var addFriendCallBack = function(res) {
					weui.toast("请求发送成功", {duration: 300});
					item.AddId = true
					if (self.userInfo.FreeAddNum) {
						self.userInfo.FreeAddNum--;
					} else if (self.userInfo.ShareAddNum) {
						self.userInfo.ShareAddNum--;
					} else if (self.userInfo.PaidAddNum) {
						self.userInfo.PaidAddNum--;
					}
				};
				var options = {
					"TaOpenId": item.openid
				};
				service.addFriend(options, addFriendCallBack);
			}
		},
        refreshMakeFriend: function (item) {
            var refreshMakeFriendCallBack = function(res) {
                weui.toast("再加成功", {duration: 300});
                if (self.userInfo.FreeAddNum) {
                    self.userInfo.FreeAddNum--;
                } else if (self.userInfo.ShareAddNum) {
                    self.userInfo.ShareAddNum--;
                } else if (self.userInfo.PaidAddNum) {
                    self.userInfo.PaidAddNum--;
                }
            }
            var options = {
                "AddId": item.AddId,
                "TaOpenId": item.openid
            };
            service.refreshMakeFriend(options, refreshMakeFriendCallBack);
        },
		listScroll: function (event) {
            self.scrollTop = Math.ceil(event.target.scrollTop); // 距离顶部高度
			if (self.noData) return
			// console.log(event)
			var clientHeight = Math.ceil(event.target.clientHeight); // 可见区高度
			var scrollHeight = Math.ceil(event.target.scrollHeight); // 滚动条高度
			// console.log(clientHeight, self.scrollTop, scrollHeight, clientHeight + self.scrollTop)
			if (clientHeight + self.scrollTop >= scrollHeight - 5) {
				self.isLoading = true;
				self.currPage++;
				self.search()
			}
		}
	}
})